import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/utils/device_utils.dart';
import 'package:tracker/pages/home/home/model/user_info_resp.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/model/base_resp.dart';
import '../../../msg/model/alarm_list_resp.dart';
import '../model/FunctionShowResp.dart';

mixin LocationPageMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
  MonitorData? monitorData;
  // 手机位置
  BMFCoordinate? phoneLocation;
  // 手机地址信息
  String? phoneAddress;
  // 是否有经纬度
  bool hasLocation = false;
  int userDeviceCount = 0;

  /// 是否解析过一次地址，假设备解析一次就行了，因为地址都一样
  bool hasReverseGeoCode = false;

  /// 假设备地址
  BMFCoordinate? nineDeviceLocation;
  String? nineDeviceAddress;

  /// 获取假设备定位地址
  /// 仅获取一次，保存在sharePreference中
  ///

  String _savedString = '';

  AlarmData? alarmData;

  Future<void> getNineDeviceAddress() async {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == false) {
      return;
    }
    var tempNineDeviceAddress = SpUtil.getString('nineDeviceAddress');
    if (hasReverseGeoCode && tempNineDeviceAddress != null && tempNineDeviceAddress.isNotEmpty) {
      nineDeviceAddress = tempNineDeviceAddress;
      return;
    }
    XLogger.info('获取假设备定位地址, latitude: ${phoneLocation?.latitude}, longitude: ${phoneLocation?.longitude}');
    if (phoneLocation == null) {
      Future.delayed(const Duration(seconds: 1), () {
        // 重试
        getNineDeviceAddress();
      });
      return;
    }
    DeviceUtils.reverseGeoCode(latitude: phoneLocation!.latitude, longitude: phoneLocation!.longitude).then((value) {
      hasReverseGeoCode = true;
      nineDeviceAddress = value;
      setState(() {});
      SpUtil.putString('nineDeviceAddress', value);
    });
  }
  Future<void> loadSavedString() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _savedString = prefs.getString('mapChooseIcon')?? "";

    });
  }




  /// 根据设备状态获取图标
  String getDeviceIcon(int? deviceStatus) {

    if (_savedString.length > 0) {
      return 'assets/images/home/' + _savedString + '.png';
    }else {
      if (deviceStatus == 1) {
        return 'assets/images/map/car_online.png';
      } else if (deviceStatus == 2) {
        return 'assets/images/map/car_offline.png';
      } else if (deviceStatus == 3) {
        return 'assets/images/map/car_sleep.png';
      }
      return 'assets/images/map/car_shutdown.png';
    }

  }
  /// 根据用户类型获取登录名
  String getLoginName(UserTypeEnum userType, UserInfoData userInfo, DeviceInfoVO deviceInfo) {
    if (userType == UserTypeEnum.phone) {
      return userInfo.phone ?? '';
    } else if (userType == UserTypeEnum.device) {
      return deviceInfo.imei ?? '';
    }
    return userInfo.nickname ?? '';
  }
  /// 获取登录用户的信息
  Future<void> fetchUserInfo() async {
    XLogger.info('获取登录用户的信息');

    await ref.read(userInfoProvider.notifier).fetchUserInfo((UserInfoData userInfoData) {
      final userType = UserTypeEnum.fromValue(userInfoData.type!);
      ref.read(userTypeProvider.notifier).state = userType;
      userDeviceCount = userInfoData.deviceCount!;
    });
  }
  void getAlarm() async {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    final postData = {
      'deviceId': deviceInfo.imei,
      'pageNum': 1,
    };
    final res =
        await post<AlarmListResp, AlarmListResp>('/deviceAlarm/list', data: postData, decodeType: AlarmListResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        final alarmList = resp.rows ?? [];
        alarmData = alarmList.firstOrNull;
        ref.read(alarmDataProvider.notifier).state = alarmData ?? AlarmData();
        setState(() {});
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取告警列表失败 code: $code msg: $msg');
    });
  }

  Future<void> getDeviceMode() async {
    final deviceInfo = ref.read(deviceInfoProvider);
    final res = await get<BaseResp, BaseResp>('$newBaseULr/device/model/list?imei=${deviceInfo.imei}',decodeType: BaseResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
          deviceInfo.deviceMode = resp.data;
        setState(() {
        });
        // ToastUtils.showToast('发送成功');
      } else {

      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
    });
  }



}
